import sys
import json

from config import getConfigParams
from logs import saveLog
from formatContent import formatContent
from requestUrl import getDocByUrl,getEntryIdByUrl

# 获取配置参数
configParams = getConfigParams(sys.argv)
url = configParams['real_url']
env = configParams['env']

# 获取回答ID
answerId = getEntryIdByUrl(configParams['base_url'])

headers = {
    'referer': 'https://www.zhihu.com',
}

# 截取url中的 questionId
questionId = url.split('/')[4:]
questionParam = url.split('/')[3:]

# 获取html文本doc，得到pq对象
doc = getDocByUrl(url, headers)

# 图片丢失，被替换成了svg
for figure in doc('figure'):
    noScriptSrc = doc(doc(figure)('img')[0]).attr('src')
    doc(doc(figure)('img')[1]).attr('src', noScriptSrc)

# 标题
title = doc('.QuestionHeader-title').text()

# 文章正文
articleContent = doc('.RichContent').html()

coverUrl = ''
# 链接是：https://www.zhihu.com/question/25401103 时，回答时通过JS渲染出来的，【暂定】取第一个回答作为内容处理
if not articleContent:
    answers = json.loads(doc('#js-initialData').html())['initialState']['entities']['answers']

    # 截止V2.0.1获取点赞量最高的回答（知乎有自己的排序算法）
    answerDict = {}
    for articleId in answers:
        answerDict[articleId] = answers[articleId]['voteupCount']
    L = list(answerDict.items())
    L.sort(key=lambda x: x[1], reverse=True)
    mostVoteupCountAnswerId = L[0][0]

    # 用商品的回答作为内容
    firstAnswer = answers[mostVoteupCountAnswerId]

    authorName = firstAnswer['author']['name']

    # 图片丢失，被替换成了svg
    pqDoc = doc(firstAnswer['content'])
    for figure in pqDoc('figure'):
        noScriptSrc = doc(doc(figure)('img')[0]).attr('src')
        doc(doc(figure)('img')[1]).attr('src', noScriptSrc)
    if doc('figure'):
        figure = doc(doc('figure')[0])
        coverUrl = doc(doc(figure)('img')).attr('src')
    articleContent = pqDoc.html()
    content = formatContent(pqDoc.html(), env=env)
else:
    # 图片丢失，被替换成了svg
    for figure in doc('figure'):
        noScriptSrc = doc(doc(figure)('img')[0]).attr('src')
        doc(doc(figure)('img')[1]).attr('src', noScriptSrc)
    if doc('figure'):
        figure = doc(doc('figure')[0])
        coverUrl = doc(doc(figure)('img')).attr('src')
    # 文章作者
    authorName = doc('.UserLink-link').text()

    # 去【李世泉】那里过滤标签
    content = formatContent(articleContent, env=env)

# 查看原文发布时间
publicTime = ''
if (questionParam[0] == 'question'):
    publicTime = \
    json.loads(doc('script[id="js-initialData"]').html())['initialState']['entities']['questions'][questionId[0]][
        'created']
elif questionParam[0] == 'answer':
    publicTime = \
    json.loads(doc('script[id="js-initialData"]').html())['initialState']['entities']['answers'][questionId[0]][
        'question']['created']

result = {
    'entry_id': answerId,
    'not_format_content': articleContent,
    'content': content,
    'author_name': authorName,
    'cover_url': coverUrl,
    'public_time': publicTime,
    'description': '',
    'title': title,
}
logData = {
    'params': sys.argv,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False))
